package com.jiang.service.impl;

import com.jiang.bean.Song;
import com.jiang.exception.PermissionOrRoleException;
import com.jiang.mapper.LuceneDao;
import com.jiang.mapper.NetSongDao;
import com.jiang.mapper.SongMapper;
import com.jiang.service.SongService;
import com.jiang.thread.MyCrawlerThread;
import com.jiang.utils.AjaxResult;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by jianggengyuan on 18/4/13.
 */
@Service
public class SongServiceImpl implements SongService {
    @Resource
    private NetSongDao netSongDao;
    @Resource
    private SongMapper songMapper;
    @Resource
    private LuceneDao luceneDao;

    @Override
    public AjaxResult getInternetSong(@Param(value = "songName") String songName) {
        List<Song> songList = null;
        try {
            //获取到网络歌曲
            songList = netSongDao.getKWSong(songName);


            //开启线程，将获取到的歌曲列表存入数据库
            MyCrawlerThread myCrawlerThread = new MyCrawlerThread(songList);
            myCrawlerThread.setSongMapper(songMapper);
            myCrawlerThread.setLuceneDao(luceneDao);
            //开启线程
            myCrawlerThread.start();

            //将歌曲列表返回给controller
            return AjaxResult.getOk(songList);
        } catch (IOException e) {
            String errorMsg = e.getMessage();
            e.printStackTrace();
            return new AjaxResult(0, "获取歌曲列表失败", errorMsg);
        }
    }

    @Override
    public void downloadMusic(@RequestParam(value = "songName") String songName,
                              @RequestParam(value = "downloadUrl") String downloadUrl,
                              HttpServletResponse response) throws IOException, PermissionOrRoleException {
        Subject subject = SecurityUtils.getSubject();
        boolean hasRole = subject.hasRole("NormalUser");
        if (hasRole) {
            netSongDao.downloadMusic(songName, downloadUrl, response);
        } else {
            throw new PermissionOrRoleException("没有下载权限");
        }
    }

    @Override
    public void insertSong(Song song) {
        songMapper.insertSong(song);
    }

    @Override
    public Song selectSong(String songId) {
        return songMapper.selectKWSong(songId);
    }

    @Override
    public List<Song> searchInner(String keyWord) {
//        return songMapper.searchInner(keyWord);
        try {
             return luceneDao.findIndex(keyWord,0,100);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
